package ticket;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 12306工具类
 *
 * Created by forvoyager@outlook.com on 2018-10-08 16:05.
 */
public class TicketUtil {

  /**
   * 将HH:mm格式时间补充为 yyyy-MM-dd HH:mm:ss
   * @param yyyyMMdd
   * @param hhmm
   * @return
   */
  public static String fillAllTimeFormat(String yyyyMMdd,String hhmm){
    return yyyyMMdd + " " + hhmm + ":00";
  }

  /**
   * 发送http请求
   * @param url
   * @return
   * @throws Exception
   */
  public static String sendRequest(String url) throws Exception {

    ignoreSsl();
    /**
     * 防止12306限制同一ip多次
     * 代理ip自己找
     */
//    System.getProperties().setProperty("proxySet", "true");
//    System.setProperty("http.proxyHost", "120.78.15.63");
//    System.setProperty("http.proxyPort", "80");

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0");
    conn.setRequestProperty("Host","kyfw.12306.cn");
    conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
    conn.setRequestProperty("Accept-Encoding","identity");
    conn.setRequestProperty("Connection","keep-alive");
    conn.setRequestProperty("Upgrade-Insecure-Requests","1");

    StringBuffer response = new StringBuffer();

    int responsecode = conn.getResponseCode();
    if (responsecode == 200) {
      String line = null;
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      while ((line = reader.readLine()) != null) {
        response.append(line);
      }
    } else {
      System.out.println("http status code:"+responsecode);
    }

    return response.toString();
  }

  public static void ignoreSsl() throws Exception {
    TrustManager tm = new IgnoreAllTM();
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, new TrustManager[]{tm}, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    HostnameVerifier hv = new HostnameVerifier() {
      public boolean verify(String urlHostName, SSLSession session) {
        return true;
      }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
  }
}
class IgnoreAllTM implements TrustManager, X509TrustManager {
  public X509Certificate[] getAcceptedIssuers() {
    return null;
  }

  public void checkServerTrusted(X509Certificate[] certs, String authType)
    throws CertificateException {
    return;
  }

  public void checkClientTrusted(X509Certificate[] certs, String authType)
    throws CertificateException {
    return;
  }
}
